package com.concurrent.synchronizeandreentrant;

import com.concurrent.base.MyRunnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName: MyExecutor
 * @Description: 学习Executor管理线程
 * @author: li
 * @Date: 2021/8/17 5:14 下午
 */
public class MyExecutor {
    public static void main(String[] args) {
        /**
         * Executors各个方法的弊端：
         * 1）newFixedThreadPool和newSingleThreadExecutor:
         * 主要问题是堆积的请求处理队列可能会耗费非常大的内存，甚至OOM。
         * 2）newCachedThreadPool和newScheduledThreadPool:
         * 主要问题是线程数最大数是Integer.MAX_VALUE，可能会创建数量非常多的线程，甚至OOM。
         */
//        Inspection '线程池不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。' options
        //为每个任务分配一个线程
        ExecutorService executorService = Executors.newCachedThreadPool();
        //只能使用一个线程
        ExecutorService executorService1 = Executors.newSingleThreadExecutor();
        //创建给定线程数的线程池
        ExecutorService executorService2 = Executors.newFixedThreadPool(6);
        for (int i = 0; i < 5; i++) {
//            executorService.execute(new MyRunnable());
//            this is a runnable classpool-1-thread-1
//            this is a runnable classpool-1-thread-4
//            this is a runnable classpool-1-thread-2
//            this is a runnable classpool-1-thread-3
//            this is a runnable classpool-1-thread-5

//            executorService1.execute(new MyRunnable());
//            this is a runnable classpool-2-thread-1
//            this is a runnable classpool-2-thread-1
//            this is a runnable classpool-2-thread-1
//            this is a runnable classpool-2-thread-1
//            this is a runnable classpool-2-thread-1

            executorService2.execute(new MyRunnable());

//            this is a runnable classpool-3-thread-1
//            this is a runnable classpool-3-thread-2
//            this is a runnable classpool-3-thread-1
//            this is a runnable classpool-3-thread-1
//            this is a runnable classpool-3-thread-3
        }
        executorService.shutdownNow();
    }
}
